package com.jinbaoty.recyclebins.server;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Build;
import android.util.Base64;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.StringUtils;
import com.jinbaoty.recyclebins.server.vo.CommandFromService;
import com.jinbaoty.recyclebins.utils.GetAndroidUniqueMark;
import com.jinbaoty.recyclebins.utils.GetDeviceId;
import com.jinbaoty.recyclebins.utils.Utils;
import com.orhanobut.logger.Logger;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.GetBuilder;
import com.zhy.http.okhttp.builder.PostFormBuilder;
import com.zhy.http.okhttp.callback.Callback;
import com.zhy.http.okhttp.callback.StringCallback;
import com.zhy.http.okhttp.request.OkHttpRequest;
import com.zhy.http.okhttp.request.RequestCall;

import org.jetbrains.annotations.NotNull;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.reflect.Parameter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class APIService {
    private static String deviceId=null;


    public static  String SERVER_URL = "https://recycle.rbdfb.com/";//"http://10.20.41.16/";//

    static{
        if(!StrUtil.endWith(SERVER_URL,"/")){
            SERVER_URL += "/";
        }
    }

    private static String KEY = "puZnTgnJ4cMmDRLI";
    private static String SIGN_APPID = "deviceId";
    private static String SIGN_SECRET = "secret";
    private static String SIGN_NONCE= "nonce";
    private static String SIGN_TIMESTAMP="timestamp";
    private static Map<String,String> signMap = new HashMap<>();


    public static void updateSecret(String secret){
        signMap.put(SIGN_SECRET,secret);
    }
    /*private static Map<String,String> getSign(){


        signMap.put(SIGN_APPID,deviceId+"");
        Date date = new Date();
        signMap.put(SIGN_TIMESTAMP,date.getTime()+"");
        signMap.put(SIGN_NONCE, UUID.fastUUID().toString().replace("-",""));

        StringBuilder signQueryKey = new StringBuilder();
        {
            String signKeys[] = {SIGN_APPID, SIGN_NONCE, SIGN_TIMESTAMP, SIGN_SECRET};
            for (String signKey : signKeys) {
                signQueryKey.append(signKey + "=" + signMap.get(signKey) + "&");
            }
            signQueryKey = new StringBuilder(StrUtil.removeSuffix(signQueryKey, "&"));
        }
        String signLog = "签名字符串："+signQueryKey+"\n";
        try {
            String sign = Utils.shaEncode(signQueryKey.toString());
            signLog+="签名："+signLog;
            signMap.put("sign",sign);
        } catch (Exception e) {
            signLog+="签名失败！";
            e.printStackTrace();
        }finally {
            Logger.d(signLog);
        }
        return signMap;
    }*/

    /**
     * 获取回收箱广告
     * @param callback 回调
     */
    public static void bannerList(Callback callback){

       /* Map<String,String> paramMap=new HashMap<>();
        paramMap.put("key",KEY);
        paramMap.put("device_id",deviceId);
        GetBuilder getBuilder = OkHttpUtils.get().url("https://recycle.rbdfb.com//api/machine/jinbao_banner");
        if(paramMap!=null){
            getBuilder.params(paramMap);
        }

        getBuilder.build().execute(callback);*/
        RequestCall requestCall=get("/api/machine/jinbao_banner");
        requestCall.execute(callback);
    }

    /**
     * 注册设备
     * @param serial1
     * @param callback
     */
/*    public static void regDevice(String serial1,Callback callback) {
        RequestCall requestCall = OkHttpUtils.get().url(SERVER_URL+"app/regDevice?s="+serial1).build();
        requestCall.execute(callback);
    }*/

    /**
     * 注册人脸
     */
    public static void regFace(byte[] faceFeature,String cardNo,Callback callback){
       // Map<String, String> headerMap = getSign();

        String url = SERVER_URL+"app/regFace" ;
        PostFormBuilder getBuilder = OkHttpUtils.post().url(url);
        Map<String,String> paramMap = new HashMap<>();
        String featureDataStr = Base64.encodeToString(faceFeature, Base64.DEFAULT);
        Logger.d("特性："+featureDataStr);
        paramMap.put("featureData",featureDataStr);
        paramMap.put("cardNo",cardNo);
        if(paramMap!=null){
            getBuilder.params(paramMap);
        }
        RequestCall build = getBuilder.build();
        build.execute(callback);
    }
    /**
     * 获取回收箱支持的所有回收类别
     * @param callback
     */
    public static void wasteTypeList(Callback callback){

      /*  Map<String,String> paramMap=new HashMap<>();
        paramMap.put("key",KEY);
        paramMap.put("device_id",deviceId);
        GetBuilder getBuilder = OkHttpUtils.get().url("https://recycle.rbdfb.com//api/machine/jinbao_catalog");
        if(paramMap!=null){
            getBuilder.params(paramMap);
        }

        getBuilder.build().execute(callback);*/

        RequestCall requestCall=get("/api/machine/jinbao_catalog");
        requestCall.execute(callback);

    }

    /**
     * 获取回收类别之下的所有回收物信息
     * @param wasteTypeId 回收类别id
     * @param callback
     */
    public static void wasteInfoList(Long wasteTypeId,Callback callback){
        Map<String,String> paramMap =new HashMap<>();
        paramMap.put("wasteTypeId",wasteTypeId+"");
        get("app/wasteInfoList",paramMap).execute(callback);
    }

    /**
     * 发送get请求
     * @param url 请求地址
     * @return
     */
    public static RequestCall get(String url){
        Map<String,String> paramMap =new HashMap<>();
        paramMap.put("key",KEY);
        paramMap.put("device_id",deviceId);
        return get(url,paramMap);
    }

    /**
     * 发送get请求，带参数
     * @param url
     * @param paramMap 参数
     * @return
     */
    public static RequestCall get(String url, Map<String,String> paramMap){
        //Map<String,String> headerMap = new HashMap<>();
        //Map<String, String> headerMap = getSign();

        url = SERVER_URL+url ;
        GetBuilder getBuilder = OkHttpUtils.get().url(url);
        if(paramMap!=null){
            getBuilder.params(paramMap);
        }
        return getBuilder.build();
    }

    /**
     * 回收箱初始化
     * @param context Activity对象
     */
    public static void init(Context context){
        final SharedPreferences deviceInfoConfig = context.getSharedPreferences("device_info", Context.MODE_PRIVATE);
        deviceId = deviceInfoConfig.getString("SIGN_APPID","");
        if(StrUtil.isBlank(deviceId)){
            deviceId = GetAndroidUniqueMark.getUniqueId(context);
            final SharedPreferences.Editor edit = deviceInfoConfig.edit();
            edit.putString("SIGN_APPID",deviceId);

            edit.commit();
        }
    }

    /**
     * 强制初始化
     * @param context
     */
/*    public static void forceInit(Context context){
        final SharedPreferences deviceInfoConfig = context.getSharedPreferences("device_info", Context.MODE_PRIVATE);
        String serial1 = deviceInfoConfig.getString("serial", "");
        serial1 = GetDeviceId.getDeviceId(context);
        final SharedPreferences.Editor edit = deviceInfoConfig.edit();
        edit.putString("serial", serial1);
        Log.d("获取deviceId：",serial1);
        String secret = deviceInfoConfig.getString(SIGN_SECRET, "");//
        Logger.d("配置文件：secret：" +secret);
        {
            if(StrUtil.isNotBlank(secret)){
                signMap.put(SIGN_SECRET,secret);
                edit.putString(SIGN_SECRET,secret);
            }
        }
        APIService.regDevice(serial1, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Logger.d(e.getMessage());
                Log.d("deviceId异常：",e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
                ResponseData responseData = JSON.parseObject(response, ResponseData.class);
                Boolean success = responseData.getSuccess();
                if (success) {
                    Object data = responseData.getData();
                    JSONObject binsInfo = (JSONObject) data;
                    Logger.d("binsInfo:%s", data);
                    Long deviceId = binsInfo.getLong("id");
                    APIService.deviceId = deviceId;
                    edit.putLong("deviceId", deviceId);
                    edit.putString("qrcodeUrl", binsInfo.getString("qrcodeUrl"));
                    edit.putString("binsNo", binsInfo.getString("binsNo"));
                    edit.commit();
                    Log.d("获取deviceId成功",deviceId+"");
                }else{
                    Log.d("获取deviceId失败",deviceId+"");
                }
            }
        });
    }*/

    /**
     * 订单是否已创建
     * @return
     */
  /*  public static ResponseData isOrderCreate() {
        //Logger.d("查询订单");
        RequestCall requestCall = get("app/orderList");
        Response execute = null;
        try {
            execute = requestCall.execute();
            ResponseBody body = execute.body();
            ResponseData responseData = JSON.parseObject(body.string(), ResponseData.class);
            return responseData;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return new ResponseData(false,500,"错误",null);
    }*/

    /**
     * 更新订单状态，用于扫码回收
     * @param wasteTypeId 垃圾类别id
     * @param orderId 订单id
     */
    public static void updateOrderWasteType(long wasteTypeId, long orderId) {
        Map<String,String> map = new HashMap<>();
        map.put("wasteTypeId",wasteTypeId+"");
        map.put("orderId",orderId+"");
        RequestCall requestCall = get("app/updateOrderWasteType", map);
        requestCall.execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(String response, int id) {

            }
        });
    }

    /**
     * 更新订单，更改两部分内容：垃圾类别与回收时拍的照片
     * @param wasteTypeId
     * @param orderId
     * @param bitmap
     * @param callback
     */
    public static void updateOrder(long wasteTypeId, long orderId, Bitmap bitmap, okhttp3.Callback callback) {
        String url = SERVER_URL+"app/updateOrderWasteType";
        Map<String,String> map = new HashMap<>();
        map.put("wasteTypeId",wasteTypeId+"");
        map.put("orderId",orderId+"");
        createOrderWithPhoto(url, map, bitmap, callback);
    }

    /**
     * 创建订单，带参数
     * @param paramMap
     * @param stringCallback
     */
    public static void createOrder(Map<String, String> paramMap, StringCallback stringCallback) {
        RequestCall requestCall = get("app/createOrder",paramMap);
        requestCall.execute(stringCallback);
    }

    /**
     * 回收结束提交订单
     * @param paramMap
     * @param stringCallback
     */
    public static void submitOrder(Map<String,String> paramMap,StringCallback stringCallback){
        RequestCall requestCall = get("app/submitOrder", paramMap);
        requestCall.execute(stringCallback);
    }


    /**
     * 获取客服相关信息
     * @param stringCallback
     */
    public static void serviceInfo(StringCallback stringCallback){
        RequestCall requestCall = get("/api/machine/jinbao_setting");
        requestCall.execute(stringCallback);

    }

    /**
     * 保存日志
     * @param errorLog
     * @param stringCallback
     */
    public static void saveLog(String errorLog,StringCallback stringCallback) {
        Map<String,String> headerMap = new HashMap<>();
        headerMap.put("deviceId",deviceId+"");
        String url = SERVER_URL+"/app/errorLog" ;
        RequestCall error = OkHttpUtils.post().url(url).headers(headerMap).addParams("error", errorLog).build();
        error.execute(stringCallback);

    }

    /**
     * 创建紧急回收订单
     * @param paramMap
     * @param stringCallback
     */
    public static void createOrderFree(Map<String, String> paramMap, StringCallback stringCallback) {
        RequestCall requestCall = get("app/createOrderFree",paramMap);
        requestCall.execute(stringCallback);
    }

    /**
     * 创建紧急回收订单带照片
     * @param paramMap
     * @param bitmap
     * @param stringCallback
     */
    public static void createOrderFreeWithPhoto(Map<String, String> paramMap,Bitmap bitmap, okhttp3.Callback stringCallback){
        String url = SERVER_URL+"app/createOrderFreeWithPhoto";
        createOrderWithPhoto(url,paramMap,bitmap,stringCallback);
    }

    /**
     * 验证管理密码
     * @param paramMap
     * @param stringCallback
     */
    public static void checkAdminPwd(Map<String,String> paramMap,StringCallback stringCallback){
        RequestCall requestCall = get("app/checkAdminPwd",paramMap);
        requestCall.execute(stringCallback);
    }

    /**
     * 创建普通订单带照片
     * @param paramMap
     * @param bitmap
     * @param stringCallback
     */
    public static void createOrderWithPhoto(Map<String,String> paramMap, Bitmap bitmap, final okhttp3.Callback stringCallback){
        String url = SERVER_URL+"/api/machine/jinbao_order_create";
        paramMap.put("key",KEY);
        paramMap.put("device_id",deviceId);
        createOrderWithPhoto(url,paramMap,bitmap,stringCallback);
    }

    /**
     * 创建普通订单带照片
     * @param url
     * @param paramMap
     * @param bitmap
     * @param stringCallback
     */
    public static void createOrderWithPhoto(String url,Map<String,String> paramMap, Bitmap bitmap, final okhttp3.Callback stringCallback){
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] bytes;
        //3.构建MultipartBody
        MultipartBody.Builder fileBodyBuilder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                ;
        if(bitmap==null){
            bytes= null;
        }else {
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
            bytes = baos.toByteArray();
            RequestBody fileBody = RequestBody.create(bytes,MediaType.parse("image/jpeg"));
            fileBodyBuilder.addFormDataPart("image", "testImage.jpg", fileBody);
        }




        for(String paramName:paramMap.keySet()){
            Logger.d("提交的参数%s",paramName,paramMap.get(paramName));
            fileBodyBuilder.addFormDataPart(paramName,paramMap.get(paramName));
        }
        RequestBody requestBody = fileBodyBuilder
                .build();

        //4.构建请求
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        OkHttpClient client = new OkHttpClient();
        //5.发送请求
        Call call = client.newCall(request);
        call.enqueue(stringCallback);
    }

    /**
     * 是否有远程指令需要执行
     * @param callback
     */
    public static void hasCommandOrder(StringCallback callback){
        RequestCall requestCall = get("app/commandList");
        requestCall.execute(callback);
    }

    /**
     * 提交远程指令执行结果
     * @param commandFromService
     * @param callback
     */
    public static void updateCommandOrder(CommandFromService commandFromService,StringCallback callback){
        Map<String,String> map = new HashMap<>();
        map.put("isRead",commandFromService.getIsRead()+"");
        map.put("isFinish",commandFromService.getIsFinish()+"");
        map.put("returnMsg",commandFromService.getReturnMsg());
        map.put("id",commandFromService.getId()+"");
        RequestCall requestCall = get("app/updateCommandStatus", map);
        requestCall.execute(callback);
    }

    /**
     * 获取卡号对应的用户
     * @param paramMap
     * @param callback
     */
    public static void queryUserByCardNo(Map<String,String> paramMap,StringCallback callback){
        paramMap.put("key",KEY);
        paramMap.put("device_id",deviceId);
        RequestCall requestCall = get("/api/machine/jinbao_user_info_by_qrcode",paramMap);
        requestCall.execute(callback);
    }

    /**
     * 获取卡号对应的用户
     * @param paramMap
     * @param callback
     */
    public static void cardNoSearch(Map<String,String> paramMap,StringCallback callback){
        paramMap.put("key",KEY);
        paramMap.put("device_id",deviceId);
        RequestCall requestCall = get("/api/machine/jinbao_user_info_by_qrcode",paramMap);
        requestCall.execute(callback);
    }

    /**
     * 提交垃圾桶回收订单
     * @param paramMap
     * @param photoBitmap
     * @param stringCallback
     */
    public static void userBinOrderWithPhoto(Map<String, String> paramMap, Bitmap photoBitmap, okhttp3.Callback stringCallback) {
        String url = SERVER_URL+"app/orderByUserBin";
        createOrderWithPhoto(url,paramMap,photoBitmap,stringCallback);
    }

    public static String getDeviceId(Context context){

        final SharedPreferences deviceInfoConfig = context.getSharedPreferences("device_info", Context.MODE_PRIVATE);
        String deviceId = deviceInfoConfig.getString("SIGN_APPID","");
        return deviceId;
    }
}
